package ejb.manager;

import java.util.Random;
import java.util.ResourceBundle;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import ejb.dao.UserDAO;
import ejb.entity.DefaultUser;
import ejb.entity.User;

@Stateless
public class DefaultUserManager implements UserManager {
	@EJB
	private UserDAO userdao;
	@EJB
	private MailManager mmail;
	
	private ResourceBundle msg;
	
	/* (non-Javadoc)
	 * @see ejb.manager.UserManager#createUser(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public User createUser(String user_name, String last_name, String first_name, String password, String email){
		User newUser = userdao.getUserByLogin(user_name);
		
		if(newUser == null){
			String code = this.getCode();
			
			newUser = new DefaultUser(user_name, last_name, first_name, password, email, code);
			newUser = userdao.create(newUser);	
			msg = ResourceBundle.getBundle("Bundle");
			String content = msg.getString("activationMsg")+code;
			mmail.send(email, content);
			return newUser;
		}else return null;	
		
	}
	
	public User getUserByLogin(String login){
		return userdao.getUserByLogin(login);
	}
	
	public void setForecast(String login, boolean state){
		User user = userdao.getUserByLogin(login);
		user.setForecast(state);
	}
	
	public String getCode(){
		
		String code = "";
		Random random = new Random();
		for(int i=0; i<10; i++){
			String a = Integer.toString(random.nextInt(100));
			code += a;
		}	
		
		return code;
	}
}
